package com.wlcorp.forcazamis.dao.storageassign.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.storageassign.IStorageAssignDAO;
import com.wlcorp.forcazamis.domain.storageassign.StorageAssign;

public class StorageAssignDAOImpl extends HibernateDaoSupport implements
		IStorageAssignDAO {

	@SuppressWarnings("unchecked")
	public List getStorageAssignList(final StorageAssign storageAssign) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select storageAssign from StorageAssign as storageAssign where 1=1 and storageAssign.deleteFlag=false");
		if(null != storageAssign){
			if(null != storageAssign.getSubmiterId() ){
				queryString.append(" and storageAssign.submiter.staffId = ").append(storageAssign.getSubmiterId());
			}
		}
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				if(null != storageAssign && null != storageAssign.getMinRownum()){
					query.setFirstResult(storageAssign.getMinRownum());
					query.setMaxResults(storageAssign.getNumPerPage());
				}
				return query.list();
			}
			
		});
	}

	public Long getStorageAssignCount(StorageAssign storageAssign) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select count(storageAssign) from StorageAssign as storageAssign where 1=1 and storageAssign.deleteFlag=false");
		if(null != storageAssign){
			if(null != storageAssign.getSubmiterId()){
				queryString.append(" and storageAssign.submiter.staffId = ").append(storageAssign.getSubmiterId());
			}
			if(null != storageAssign.getType()){
				queryString.append(" and storageAssign.type = ").append(storageAssign.getType());
			}
		}
		return (Long)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				return query.uniqueResult();
			}
			
		});
	}

	public StorageAssign getStorageAssignById(Long storageAssignId) throws DaoException {
		return (StorageAssign)getHibernateTemplate().get(StorageAssign.class,storageAssignId);
	}

	public void deleteStorageAssign(StorageAssign storageAssign) throws DaoException {
		storageAssign.setDeleteFlag(true);
		getHibernateTemplate().update(storageAssign);
	}

	public void saveStorageAssign(StorageAssign storageAssign) throws DaoException {
		getHibernateTemplate().saveOrUpdate(storageAssign);
	}


}
